package com.ice.common;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;


import com.fasterxml.jackson.databind.ObjectMapper;


public class IceLog {
	
	/**
	 * 根据当前时间转换成yyyy/MM/dd HH:mm:ss的时间格式
	 * 
	 * @return
	 */
	
	public static String  getTime(){
			SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			Date date = new Date(System.currentTimeMillis());
			return format.format(date);
	}

	/**
	 * 生成日志信息
	 * @param startTime
	 * @param operatorName
	 * @param message
	 * @param objects
	 * @return
	 */
	public static Map<String, Object>  setContent(long startTime,String operatorName,String message,Object...objects){
		
		//获取当前系统时间
		long endTime = System.currentTimeMillis();
		//计算操作使用时间
		long spend_time = endTime - startTime;
		//获取当前线程id
		long currentThreadId = Thread.currentThread().getId();
		String threadName = Thread.currentThread().getName();
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("时间", getTime());
		map.put("当前线程", String.format("%s-%s", threadName,currentThreadId));
		map.put("操作名称", operatorName);
		map.put("操作时间",String.format("%s 毫秒", spend_time));
		map.put("操作详细信息", message);
		if(objects!=null && objects.length>0){
			for (int i = 0; i < objects.length; i++) {
				map.put("额外信息"+i, objects[i]);
			}
		}
		return map;
	}
	
	
	/**
	 * 打印最后的信息
	 * @param startTime
	 * @param operatorName
	 * @param message
	 * @param objects
	 * @return
	 */
	public static String printLog(long startTime,String operatorName,String message,Object...objects){
	
		
		Map<String, Object> map = setContent(startTime,operatorName, message, objects);
	
		ObjectMapper mapper = new ObjectMapper();
		String json = null;
		try {
			json  = mapper.writeValueAsString(map);
			//int a=7/0; //测试异常情况下是否打印日志
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			json=map.toString();
		}
	 	
		return json;	
	}
	
  

}
